﻿package {
	import flash.display.*;
	import flash.events.*;
	import flash.net.*;
	import flash.text.*;
	
	public class ChatClient extends Sprite {
		private var host:String;
		private var port:int;
		private var socket:Socket;
		private var chatArea:TextField;
		
		public function ChatClient(h:String, p:int, ca:TextField) {
			this.host = h;
			this.port = p;
			this.chatArea = ca;
		}
		
		public function sendMessage(msg:String):void {
			msg += "\n";
			
			try {
				this.socket.writeUTFBytes(msg);
				this.socket.flush();
				trace("Message sent: " + msg);
			}
			catch(e:Error) {
				trace("Error sending data: " + e);
			}
		}
		
		private function receiveData(msg:String):void {
			trace("Message received: " + msg);
			this.chatArea.appendText(msg + "\n");
		}
		
		public function connect():Boolean {
			this.socket = new Socket(this.host, this.port);
			this.socket.addEventListener(Event.CONNECT, socketConnect);
			this.socket.addEventListener(Event.CLOSE, socketClose);
			this.socket.addEventListener(IOErrorEvent.IO_ERROR, socketError);
			this.socket.addEventListener(SecurityErrorEvent.SECURITY_ERROR, securityError);
			this.socket.addEventListener(ProgressEvent.SOCKET_DATA, socketData);
				
			try {
				this.socket.connect(this.host, this.port);
			}
			catch (e:Error) {
				trace("Error on connect: " + e);
				
				return false;
			}
			
			return true;
		}
		
		private function socketConnect(event:Event):void {
			trace("Connected: " + event);
		}

		private function socketData(event:ProgressEvent):void {
			trace("Receiving data: " + event);
			receiveData(this.socket.readUTFBytes(this.socket.bytesAvailable));
		}
		
		private function socketClose(event:Event):void {
			trace("Connection closed: " + event);
			this.chatArea.appendText("Connection lost." + "\n");
		}
		
		private function socketError(event:IOErrorEvent):void {
			trace("Socket error: " + event);
		}
		
		private function securityError(event:SecurityErrorEvent):void {
			trace("Security error: " + event);
		}
	}
}